<template>
	<view class="wrap">
		<view v-if="!viewShow"
			style="height: 80vh;display: flex;justify-content: center;align-items: center;padding: 0 30px;">
			<!-- <js-lang title="login.title" :showBtn="true"></js-lang> -->
			<view style="width: 100%;">

				<view class="logo">
					<image src="/static/jeesite/logo200.png" mode="aspectFit"></image>
				</view>
				<view v-if="isBind">
					<view class="list">
						<view class="list-call">
							<u-icon class="u-icon" size="40" name="phone"></u-icon>
							<input class="u-input" disabled type="text" v-model="username" maxlength="32" placeholder="请先获取手机号" />
						</view>
					</view>
					<view style="padding: 20px;">
						<button style="background-color: #3E97B0;color: #fff;border: none;" open-type="getPhoneNumber"
							@getphonenumber="getPhoneNumber" plain="true">获取手机号</button>
					</view>
				</view>
				<view v-if="xcxMessage"
					style="margin-top: 20px;font-size: 20px;color: red;display: flex;justify-content: center;align-items:center;">
					<u-icon name="error-circle" size="50"></u-icon>
					<text style="margin-left: 5px;">
						{{xcxMessage}}
					</text>
				</view>
				<view v-if="!xcxMessage" style="text-align: center;margin-top: 20px;font-size: 20px;">
					自动登录中...
				</view>
			</view>
		</view>

		<view v-else style="height: 80vh;display: flex;justify-content: center;align-items: center;">

			<view class="">
				<!-- <view class="logo">
					<image src="/static/jeesite/logo200.png"></image>
				</view> -->
				<view class="logo">
					<image src="/static/jeesite/logo200.png" mode="aspectFit"></image>
				</view>

				<view v-if="viewShow=='加载'" style="text-align: center;margin-top: 20px;font-size: 20px;">
					加载中...
				</view>

				<view v-else
					style="margin-top: 20px;font-size: 20px;color: red;display: flex;justify-content: center;align-items:center;">
					<u-icon name="error-circle" size="50"></u-icon>
					<text style="margin-left: 5px;">
						{{viewShow}}
					</text>

				</view>

			</view>
		</view>


		<u-popup v-model="show" mode="bottom" height="260px" :mask-close-able='false'>
			<view style="width: 100%;height: 260px;padding: 10px 50px;background-color: #eee;font-size: 12px;">
				<view class="">授权申请</view>
				<view style="margin: 10px 0;">获取你的昵称、头像</view>
				<view
					style="border-top:1px solid #bcbcbc;border-bottom:1px solid #bcbcbc;padding: 10px 0;display: flex;margin-bottom: 10px;">
					<!-- <view style="width: 50px;height: 50px; margin-right: 10px;">
						<open-data type="userAvatarUrl"></open-data>
					</view>
					<view class="">
						<open-data type="userNickName"></open-data>
						<view style="color: #aaa;">
							微信个人信息
						</view>
					</view> -->
					<view style="width: 70px;height: 70px; margin-right: 10px;">
						<button style="width: 70px;height: 70px;display: flex;padding: 0;" open-type="chooseAvatar"
							@chooseavatar="onChooseAvatar">
							<image style="width: 70px; height: 70px;" :src="avatarUrl"></image>
						</button>
					</view>
					<input v-model="nickname1" @change="getNickname" type="nickname" class="weui-input"
						placeholder="请输入昵称" />
				</view>
				<view style="display: flex;justify-content: center;">
					<view @click="reject"
						style="width: 80px;height: 30px;line-height:30px;text-align: center;margin-right: 20px;background-color: #fff;color: #00aa00;">
						拒绝</view>
					<view v-if="nickname1 && avatarUrl" @click="allow"
						style="width: 80px;height: 30px;line-height:30px;text-align: center;background-color: #00aa00;color: #fff;">
						允许</view>
					<view v-else
						style="width: 80px;height: 30px;line-height:30px;text-align: center;background-color: #aaa;color: #eee;">
						允许</view>
				</view>
			</view>


		</u-popup>
	</view>
</template>
<script>
	/**
	 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
	 */
	import base64 from '@/common/base64.js';
	import config from '@/common/config.js';
	import {
		mapMutations
	} from "vuex";
	export default {
		data() {
			return {
				isBind: false,
				xcxMessage: '',
				viewShow: '',
				logincode: '',
				nickname1: '',
				avatarUrl: '',
				show: false,
				username: '',
				password: '',
				// username: 'system',
				// password: 'win2003..',
				showPassword: false,
				remember: true,
				isValidCodeLogin: false,
				validCode: '',
				imgValidCodeSrc: null,
				baseUrlList: config.baseUrlList,
				baseUrlValue: ''
			};
		},
		onLoad() {

			let _this = this;
			let res1 = wx.getSystemInfoSync()
			console.log(res1, 'res1');
			// 企业微信
			if (res1.environment === 'wxwork') {
				this.viewShow = '加载'
				// setTimeout(()=>{
				// 	this.viewShow = '企业微信暂未授权微信！！！'
				// 	// _this.$u.vuex('vuex_user', {
				// 	// 	..._this.vuex_user,
				// 	// 	wxOpenid: res.data
				// 	// });
				// },3000)
				uni.qy.login({
					suiteid: '1000043', //非必填，第三方应用的suiteid，自建应用不填。若第三方小程序绑定多个第三方应用时，建议填上该字段
					success: function(res) {
						_this.$u.api.zfgs.wechatCallback({
							code: res.code
						}).then((resp) => {
							console.log(resp, 'wechatCallback======');
							if (resp.result == 'true') {
								_this.$u.api.authInfo().then((res) => {
									_this.setAuditList(res.stringPermissions)
								})
								_this.$u.api.menuTree().then((res) => {
									_this.setMenuList(res)
								})
								setTimeout(() => {
									_this.$u.vuex('vuex_user', {
										..._this.vuex_user,
										environment: 'wxwork'
									});
									uni.reLaunch({
										url: '/pages/zfgs/index/notice/index'
									});
								}, 500);
							} else {
								// _this.$u.toast(resp.message || '未连接服务器');
								_this.viewShow = resp.message || '未连接服务器'
							}
						})
					}
				});
			} else {
				let that = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						that.$u.api.zfgs.weixinMaCallback({
							code: loginRes.code,
							encryptedData: '',
							iv: '',
							isBind: '0'
						}).then(resp => {
							if (resp.result == 'true') {
								that.$u.api.authInfo().then((res1) => {
									that.setAuditList(res1.stringPermissions)
								})
								that.$u.api.menuTree().then((res2) => {
									that.setMenuList(res2)
								})
								uni.reLaunch({
									url: '/pages/zfgs/index/notice/index'
								});
							} else {
								if (resp.message.includes('[noBind]')) {
									that.isBind = true
									that.xcxMessage = '请获取手机号绑定账号'
								} else {
									that.xcxMessage = resp.message
								}
								// uni.showModal({
								// 	title: '提示',
								// 	content: resp.message || '未连接服务器',
								// 	showCancel: false,
								// 	success: function(res) {}
								// });
								// that.$u.toast(resp.message);
							}
						});
					}
				});
			}



			// this.baseUrlList.forEach(item => {
			// 	if (item.baseUrl == this.vuex_baseUrl){
			// 		this.baseUrlValue = item.value;
			// 		return;
			// 	}
			// });
		},
		methods: {
			...mapMutations("auth", ["setAuditList"]),
			...mapMutations("auth", ["setMenuList"]),
			getNickname(e) {
				this.nickname1 = e.detail.value
				console.log(e, 'getNickname===');
			},
			onChooseAvatar(e) {
				console.log(e, '===');
				this.avatarUrl = e.detail.avatarUrl
			},
			showPass() {
				this.showPassword = !this.showPassword;
			},
			async getPhoneNumber(e) {
				console.log(e);
				let that = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						that.$u.api.zfgs.weixinMaCallback({
							code: loginRes.code,
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv,
							isBind: '1'
							// userCode: _this.vuex_user.userCode,
						}).then(res => {
							if (res.result == 'true') {
								that.$u.api.authInfo().then((res1) => {
									that.setAuditList(res1.stringPermissions)
								})
								that.$u.api.menuTree().then((res2) => {
									that.setMenuList(res2)
								})
								uni.reLaunch({
									url: '/pages/zfgs/index/notice/index'
								});
							} else {
								if (res.message.includes('[noBind]')) {
									that.isBind = true
									that.xcxMessage = '请获取手机号绑定账号'
								} else {
									that.xcxMessage = res.message
								}
							}
						});
					}
				});

			},
			refreshImgValidCode(e) {
				if (this.vuex_token == '') {
					this.$u.api.index().then(res => {
						this.imgValidCodeSrc = this.vuex_config.baseUrl + '/validCode?__sid=' +
							res.sessionid + '&t=' + new Date().getTime();
					});
				} else {
					this.imgValidCodeSrc = this.vuex_config.baseUrl + '/validCode?__sid=' +
						this.vuex_token + '&t=' + new Date().getTime();
				}
				this.validCode = '';
			},
			reject() {
				this.show = false;
				this.$u.api.logout().then(res => {});
			},
			async allow() {
				// this.$u.api.yysh.bindWxOpenid({
				// 	wxOpenid:uni.getStorageSync('loaclOpenId'),
				// 	userCode:this.vuex_user.userCode,
				// }).then(res => {
				// 		this.$u.vuex('vuex_user',{...this.vuex_user,wxOpenid:res.user.wxOpenid});
				// 		uni.setStorageSync('wxavatarUrl', this.avatarUrl)
				// 		setTimeout(() => {
				// 			uni.reLaunch({
				// 				url: '/pages/zfgs/index/notice/index'
				// 			});
				// 		}, 500);

				// 	});

				let _this = this;
				this.$u.api.getOpenId({
					code: _this.logincode,
					userCode: _this.vuex_user.userCode,
				}).then(res => {
					if (res.result == "true") {
						_this.$u.vuex('vuex_user', {
							..._this.vuex_user,
							wxOpenid: res.data
						});
						uni.setStorageSync('wxavatarUrl', _this.avatarUrl)
						// setTimeout(() => {
						// 	uni.setStorageSync('HBusername', this.username);
						// 	uni.setStorageSync('HBpassword', this.password);
						// 	uni.reLaunch({
						// 		url: '/pages/zfgs/index/notice/index'
						// 	});
						// }, 500);
						uni.setStorageSync('HBusername', this.username);
						uni.setStorageSync('HBpassword', this.password);
						uni.reLaunch({
							url: '/pages/zfgs/index/notice/index'
						});
						// this.subscribe()
					} else {
						_this.$u.toast(res.message);
					}

				});


			},
			submit() {
				let _that = this
				if (this.username.length == 0) {
					this.$u.toast('请输入账号');
					return;
				}
				if (this.password.length == 0) {
					this.$u.toast('请输入密码');
					return;
				}
				this.$u.api.login({
						username: base64.btoa(this.username),
						password: base64.btoa(this.password),
						validCode: base64.btoa(this.validCode),
						param_deviceType: 'mobileApp',
						param_remember: this.remember,
						param_loginType: '2'
					})
					.then(res => {
						console.log(res, 'res======');
						if (res.result == 'true') {
							this.$u.api.authInfo().then((res) => {
								this.setAuditList(res.stringPermissions)
							})
							this.$u.api.menuTree().then((res) => {
								this.setMenuList(res)
							})
							// uni.setStorageSync('HBusername', this.username);
							// uni.setStorageSync('HBpassword', this.password);
							// setTimeout(() => {
							// 	uni.reLaunch({
							// 		url: '/pages/zfgs/index/notice/index'
							// 	});
							// }, 500);

							if (!res.user.wxOpenid) {
								uni.login({
									provider: 'weixin',
									success: function(loginRes) {
										_that.logincode = loginRes.code
									}
								});
								this.show = true
							} else {
								uni.setStorageSync('HBusername', this.username);
								uni.setStorageSync('HBpassword', this.password);
								uni.reLaunch({
									url: '/pages/zfgs/index/notice/index'
								});
							}
						} else {
							uni.showModal({
								title: '提示',
								content: res.message || '未连接服务器',
								showCancel: false,
								success: function(res) {}
							});
							// this.$u.toast(res.message || '未连接服务器');
						}
						if (res.isValidCodeLogin) {
							this.isValidCodeLogin = true;
							this.refreshImgValidCode();
						}
					});
			},
			wxLogin(res) {
				this.$u.toast('微信登录');
				let that = this;
				uni.login({
					provider: 'weixin',
					success: function(wxRes) {
						uni.showLoading('正在登录中...');
						console.error(wxRes);
						// 获取登录的token
						uni.setData('weixinToken', wxRes.code);
						// 获取登录的unionid 这个还是在开放平台做了 公众号 小程序 微信登录app关联才会有
						uni.setData('unionid', wxRes.authResult.unionid);
						// 获取openid
						uni.setData('weixinOpenid', wxRes.authResult.openid);
						// 这里吧数据全部提交给后台核验，有没有注册 注册了 后台代码会请求接口
						// String s = HttpClient.doGet("https://api.weixin.qq.com/sns/userinfo?access_token="
						//  + loginInfo.getToken() + "&openid=" + loginInfo.getOpenid()); 获取头像和昵称
						that.$u.postJson('/user/loginApp', {
								token: wxRes.authResult.access_token,
								unionid: wxRes.authResult.unionid,
								openid: wxRes.authResult.openid
							})
							.then(res => {
								if (res.status === 0) {
									// 绑定手机号直接登录
									that.getUserInfo(res.data.userId, res.data.uuid);
								} else {
									// 没有绑定手机号让绑定手机号
									uni.navigateTo({
										url: '/pages/public/wxmobile'
									});
								}
							});
					}
				});
			},
			qqLogin() {
				this.$u.toast('QQ 登录');
			},
			updateBaseUrl() {
				this.baseUrlList.forEach(item => {
					if (item.value == this.baseUrlValue) {
						this.vuex_config.baseUrl = item.baseUrl;
						this.$u.vuex('vuex_baseUrl', this.vuex_config.baseUrl);
						this.$u.http.setConfig({
							baseUrl: this.vuex_config.baseUrl
						});
						this.$u.toast('切换成功！');
						return;
					}
				});
			}
		}
	};
</script>
<style lang="scss">
	@import 'index.scss';

	.logo {
		width: 500rpx;
		height: 260rpx;
		// background: rgba(59, 121, 235, 1);
		// box-shadow: 0rpx 5rpx 20rpx 5rpx rgba(45, 127, 235, 0.5);
		// border-radius: 50%;
		// border-radius: 10px;
		margin: 70rpx auto 10rpx auto;
	}

	.logo image {
		width: 500rpx;
		height: 260rpx;
		border-radius: 50%;
	}

	.base-url js-select {
		width: 100%;
	}

	.button {
		margin: 30rpx auto 0;
		// background-color: #3E97B0 !important;
		background: linear-gradient(-90deg, #3E97B0, #3E97B0);
	}

	.footer {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		text-align: center;
		color: #46afff;
		height: 40rpx;
		line-height: 40rpx;
		font-size: 35rpx;
		margin-top: 60rpx;
	}

	.footer text {
		font-size: 30rpx;
		margin-left: 25rpx;
		margin-right: 25rpx;
	}

	.oauth2 {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		margin: 55rpx 100rpx;

		image {
			height: 100rpx;
			width: 100rpx;
		}
	}
</style>